package com.egdigital.allzic.service;

import android.os.Handler;

public class Scheduler {

	// DATA
	private OnScheduleTimeListener	mListener;
	private Handler					mHandler;
	private int						mInterval;			// Between each executions in milli
	private static final int		DELAY		= 100;	// before first execution
	private boolean					mIsTimerRunning;
	private int						mCount		= 0;
	private int						mCountMax	= 1;
	private Mode					mMode;

	public static enum Mode {
		ASC, // count
		DESC, // decount
	}

	public static interface OnScheduleTimeListener {

		public void onScheduleTime(int count);
	}

	public Scheduler(int interval, int countMax, Mode mode) {
		super();
		if (countMax == -1) {
			mCountMax = Integer.MAX_VALUE;
		} else {
			if (mode.equals(Mode.DESC)) {
				mCount = countMax;
			}
			mCountMax = countMax;
		}
		mMode = mode;
		mInterval = interval;
		mHandler = new Handler();
	}

	private final Runnable	mRunnable	= new Runnable() {

											@Override
											public void run() {
												// Do stuff
												mListener.onScheduleTime(mCount);
												if (mMode.equals(Mode.ASC)) {
													mCount++;
												} else {
													if (mCount == 0) {
														stopTimer();
														return;
													}
													mCount--;
												}
												// Repeat
												mHandler.postDelayed(mRunnable, mInterval);
											}
										};

	public void setOnScheduleTimeListener(OnScheduleTimeListener listener) {
		mListener = listener;
	}

	public void startTimer() {
		mIsTimerRunning = true;
		mHandler.postDelayed(mRunnable, DELAY);
	}

	public void stopTimer() {
		mIsTimerRunning = false;
		mHandler.removeCallbacks(mRunnable);
	}

	public boolean isTimerRunning() {
		return mIsTimerRunning;
	}
}
